import {
  cutpriceHome,
  cutpriceCut,
  productsFeatured,
  addFormId,
  createQrcode,
  cutpriceFriendHome,
  loginWithCode,
  cutBeShared,
  cutRegle
} from "../../../api.js"
var app = getApp().globalData
Page({
  data: {
    form: [],
    header_pic: "",
    countDay: '',
    countDownHour: '',
    countDownMinute: '',
    countDownSecond: "",
    interested_list: [],
    alert_none: false,
    alert_erwei: '',
    shar_bj: '',
    topimageurl: '',
    alert_upType: '',
    many_alert: false,
    alert_num: '',
    rule_text: [],
    ruler_alert: false,
    hidd:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(app)
    this.setData({
      options
    })
      this.checkUserInfo()
      cutRegle().then(res => {
        console.log(res)
        this.setData({
          rule_text: res.data.data.regle
        })
      })
  },
  onShow: function(options) {
    getApp().startpage(new Date().getTime())
    
  },
  //确认是否授权
  checkUserInfo() {
    const xp = this;
    wx.getSetting({
      success: function(res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.navigateTo({
            url: '/pages/public/shouquan/shouquan',
          })
        } else {
          wx.getUserInfo({
            success(res) {
              xp.loginWithCode(res.userInfo)
            }
          })
        }
      }
    })
  },
  //登陆
  loginWithCode(userInfo) {
    const xp = this
    wx.login({
      success({
        code
      }) {
        loginWithCode({
          ...userInfo,
          code,
          business_id: app.businessId
        }).then(res => {
          if (res.data.code === 666) {
            app.Store = res.data.data
            if (xp.data.options.parent_id == app.Store.user.id){
              wx.redirectTo({
                url: '/pages/activity/details/details?id=' + xp.data.options.product_id,
              })
            }
            var token = res.data.data.token;
            var business_id = app.businessId
          }else{
            wx.showToast({
              title: res.data.msg,
              icon:'none'
            })
          }
          xp.initialization(xp.data.options)
          
        })
      }
    })
  },
  //推荐列表砍价
  goactiv(e) {
    var id = e.currentTarget.dataset.id
    var index = e.currentTarget.dataset.index
    console.log(this.data.options)
    var that = this
    wx.redirectTo({
      url: '/pages/activity/details/details?id=' + id + '&enter_type=7&label=2&position=' + index,
    })
  },
  // 页面初始化
  initialization(options) {
    var that = this
    cutpriceFriendHome(app.Store.token, options.parent_id, options.product_id).then(res => {
      if (res.data.code == 666) {
        that.countDown(res.data.data.time.activity_end_time, res.data.data.time.now)
        that.setData({
          form: res.data.data,
          hidd:false
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
    that.recommend(options)
    if (options.source) {
      cutBeShared(app.Store.token, options.source, options.parent_id, options.product_id).then(res => {
          console.log(res)
      })
    }
  },
  //推荐商品
  recommend(options) {
    var that = this
    productsFeatured(app.Store.token, options.product_id).then(res => {
      if (res.data.code == 666) {
        that.setData({
          interested_list: res.data.data
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  onHide: function() {
    getApp().endpage(new Date().getTime())
  },
  // 倒计时
  countDown(endTime, nowTime) {
    var now = new Date(nowTime.replace(/\-/g, "/")).getTime()
    var end_time = new Date(endTime.replace(/\-/g, "/")).getTime()
    var totalSecond = (end_time - now) / 1000
    var interval = setInterval(function() {
      var second = totalSecond;
      var day = Math.floor((second) / 3600 / 24);
      var daStr = day.toString();
      var hr = Math.floor((second) / 3600);
      var hrStr = hr.toString() % 24;
      if (hrStr.length == 1) hrStr = '0' + hrStr;
      var min = Math.floor((second - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;
      var sec = second - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;
      this.setData({
        countDay: daStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        // wx.showToast({
        //   title: '活动已结束',
        // });
        this.setData({
          countDay: '0',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          // jieshu: true
        });
      }
    }.bind(this), 1000);
  },
  //返回首页
  goHome(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    wx.switchTab({
      url: '/pages/tabBar/index/index',
    })
  },
  foot_goHome(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    wx.switchTab({
      url: '/pages/tabBar/index/index',
    })
  },
  // 分享砍价
  form_share(e) {
    var id = e.detail.formId
    var that = this
    addFormId(app.Store.token, id, 1).then(res => {})
    console.log(this.data.options.product_id)
    console.log(this.data.options.parent_id)
    cutpriceCut(app.Store.token, this.data.options.product_id, this.data.options.parent_id).then(res =>{
      if(res.data.code == 666){
        that.setData({
          many_alert:true,
          alert_num: res.data.data.cut_price
        })
        that.initialization(that.data.options)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  // 定义分享
  onShareAppMessage(res) {
    return {
      title: "芮享邀你来砍价，购买奢侈品，最低只要600起",
      imageUrl: this.data.form.cut_product_detail[0].pic_url,
      path: '/pages/activity/orderDetails/orderDetails?parent_id=' + this.data.options.parent_id + '&product_id=' + this.data.options.product_id +'&source=2',
    }
  },
  form_share_two(e){
    var id = e.detail.formId
    var that = this
    addFormId(app.Store.token, id, 1).then(res => { })
  },
  //查看订单
  look_batchcode(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    var batchcode = this.data.form.batchcode
    wx.navigateTo({
      url: '/pages/money/detail/detail?batchcode=' + batchcode,
    })
  },
  poster(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    var that = this
    createQrcode(getApp().globalData.Store.token).then(res => {
      if (res.data.code == 666) {
        that.setData({
          alert_erwei: res.data.data.key
        })
        if (that.data.alert_upType == 0) {
          wx.showLoading({
            title: '正在生成分享图片',
          })
          wx.downloadFile({
            url: 'https://document.growthupup.com/alert_img_bjj.png',
            success: function(res) {
              that.setData({
                shar_bj: res.tempFilePath
              })
              wx.downloadFile({
                url: getApp().globalData.Store.user.topimageurl,
                success: function(res) {
                  that.setData({
                    topimageurl: res.tempFilePath,
                  })
                  wx.downloadFile({
                    url: that.data.alert_erwei,
                    success: function(res) {
                      wx.hideLoading()
                      that.setData({
                        alert_erwei: res.tempFilePath,
                        alert_none: true,
                        alert_upType: 1
                      })
                      that.canvasImg()
                    }
                  })
                }
              })
            }
          })
        } else {
          wx.downloadFile({
            url: that.data.alert_erwei,
            success: function(res) {
              wx.hideLoading()
              that.setData({
                alert_erwei: res.tempFilePath,
                alert_none: true,
              })
              that.canvasImg()
            }
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  alert_off() {
    this.setData({
      alert_none: false
    })
  },
  //去购买
  go_buy(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    var fomr = this.data.form.cut_product_detail[0]
    let keyArr = Object.keys(fomr)
    let map = Object.create(null)
    let k;
    for (let i = 0, l = keyArr.length; i < l; i++) {
      k = keyArr[i]
      map[k] = encodeURIComponent(fomr[k])
    }
    wx.navigateTo({
      url: '/pages/money/settlement/settlement?product=' + JSON.stringify([map]) + '&order_enter_type=3'
    })
  },
  go_share(e){
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
  },
  //砍价成功购买
  go_success_buy(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    var fomr = this.data.form.cut_product_detail[0]
    let keyArr = Object.keys(fomr)
    let map = Object.create(null)
    let k;
    for (let i = 0, l = keyArr.length; i < l; i++) {
      k = keyArr[i]
      map[k] = encodeURIComponent(fomr[k])
    }
    wx.navigateTo({
      url: '/pages/money/settlement/settlement?product=' + JSON.stringify([map]) + '&order_enter_type=4'
    })
  },
  close_alert() {
    this.setData({
      many_alert: false
    })
  },
  may_list(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    wx.navigateTo({
      url: '/pages/activity/myList/myList',
    })
  },
  gotop(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => {})
    wx.navigateTo({
      url: '/pages/activity/list/list',
    })
  },
  gotopp(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    wx.switchTab({
      url: '/pages/tabBar/index/index'
    })
  },
  formSubmit_homePage(e) {
    var id = e.detail.formId
    addFormId(app.Store.token, id, 1).then(res => { })
    this.setData({
      ruler_alert: true
    })
  },
  close_ruler() {
    this.setData({
      ruler_alert: false
    })
  },
})